from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.views import APIView
from goods.models import GoodsCategory
from rest_framework.response import Response
from goods.models import SKU
from goods.serializers import GoodsSerializers, SKUIndexSerializers, GoodsHistorySerializers
from goods.utils import GoodsPage
from rest_framework.filters import OrderingFilter
from drf_haystack.viewsets import HaystackViewSet


class CategorieView(APIView):
    def get(self, request, pk):
        # 获取分类信息  第三及分类
        cat3 = GoodsCategory.objects.get(id=pk)
        # 根据第三级分类 获取第二季和第二级分类
        cat2 = cat3.parent
        cat1 = cat2.parent

        return Response(
            {
                'cat1': cat1.name,
                'cat2': cat2.name,
                'cat3': cat3.name
            }
        )


# 获取某一种特定商品信息，返回给前端
class GoodsView(ListAPIView):
    serializer_class = GoodsSerializers
    # 指定分页器
    pagination_class = GoodsPage

    # 指定排序
    filter_backends = [OrderingFilter]
    ordering_fields = ['price', 'sales', 'create_time']

    # 获取商品的信息
    def get_queryset(self):
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


class SKUSearchViewSet(HaystackViewSet):
    """
        SKU搜索
        """
    index_models = [SKU]  # 指定检索对像模型类

    serializer_class = SKUIndexSerializers
    # 指定分页器
    pagination_class = GoodsPage


# 定义一个用户浏览商品的视图类
class GoodHistoryView(CreateAPIView,ListAPIView):

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return GoodsHistorySerializers
        else:
            return GoodsSerializers

    # 从缓存中获取商品id
    def get_queryset(self):
        redis_conn = get_redis_connection('history')
        user = self.request.user
        # 根据id查询商品对象
        skus_id = redis_conn.lrange('history_%s' % user.id, 0, 10)
        return SKU.objects.filter(id__in=skus_id)
